﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HDT.GUI;
using DTO;
using BLL;

namespace HDT
{
    public partial class FrmLapHD : Form
    {
        private string PRODUCT_IMAGE_FOLDER = "Image\\_Product\\";
        private NhanVienDTO nhanVien;
        private List<ChiTietHoaDonDTO> dsChiTiet;
        private List<MatHangDTO> dsMatHang;
        private List<LoaiMatHangDTO> dsLoaiMH;
        private HoaDonDTO hoaDonTam;

        public FrmLapHD()
        {
            InitializeComponent();
            nhanVien = new NhanVienDTO();
            dsMatHang = new List<MatHangDTO>();
            dsChiTiet = new List<ChiTietHoaDonDTO>();
            hoaDonTam = new HoaDonDTO();
        }

        public FrmLapHD(DTO.TKDangNhapDTO taiKhoan)
            : this()
        {
            try
            {
                nhanVien = new NhanVienBLL().GetByID(taiKhoan.MaNhanVien);
                hoaDonTam.MaNhanVien = nhanVien.MaNhanVien;
            }
            catch
            { }
        }

        private void btnXemGio_Click(object sender, EventArgs e)
        {
            FrmGioHang frm_GioHang = new FrmGioHang(hoaDonTam, dsChiTiet);
            frm_GioHang.UpdateChiTiet = new FrmGioHang.MyDelegete(UpdateChiTiet);
            frm_GioHang.RemoteChiTiet = new FrmGioHang.MyDelegete(RemoveChiTiet);
            frm_GioHang.SetHoaDon = new FrmGioHang.DelegateSetInfo(SetHoaDonInfo);
            frm_GioHang.ResetAll = new FrmGioHang.DelegateReset(ResetAll);
            frm_GioHang.RemoveAll = new FrmGioHang.DelegateReset(RemoveAll);
            frm_GioHang.ShowDialog();
        }

        private void LoadLoaiMH()
        {
            cboLoaiMH.Items.Add("Tất cả");
            foreach (LoaiMatHangDTO loai in dsLoaiMH)
            {
                cboLoaiMH.Items.Add(loai.TenLoaiMatHang);
            }
        }

        private void SearchMatHang()
        {
            string condition = "TrangThai = 1 AND TenMatHang LIKE '%" + txtTenMH.Text.Trim() + "%'"
                + (cboLoaiMH.SelectedIndex == 0 ? "" : " AND LoaiMatHang = '" + dsLoaiMH[cboLoaiMH.SelectedIndex - 1].MaLoaiMatHang + "'");
            string orderBy = "TenMatHang " + (cboSXGia.SelectedIndex == 0 ? "ASC" : "DESC");
            dsMatHang = new MatHangBLL().Select(condition, orderBy);
            LoadDSMatHang();
        }

        private void LoadDSMatHang()
        {
            dgvMH.Rows.Clear();
            foreach (MatHangDTO matHang in dsMatHang)
            {
                DataGridViewRow row = (DataGridViewRow)dgvMH.Rows[0].Clone();
                row.Cells[0].Value = matHang.MaMatHang;
                row.Cells[1].Value = matHang.TenMatHang;
                try
                {
                    foreach (LoaiMatHangDTO loai in dsLoaiMH)
                    {
                        if (loai.MaLoaiMatHang == matHang.MaLoaiMatHang)
                        {
                            row.Cells[2].Value = loai.TenLoaiMatHang;
                            break;
                        }
                    }
                }
                catch { }
                row.Cells[3].Value = matHang.DonViTinh;
                row.Cells[4].Value = new MatHangBLL().SoLuongTon(matHang.MaMatHang).ToString("#,##0");
                dgvMH.Rows.Add(row);
            }
        }

        private void FrmLapHD_Load(object sender, EventArgs e)
        {
            try
            {
                dsLoaiMH = new LoaiMatHangBLL().Select("TrangThai = 1");
            }
            catch { }
            LoadLoaiMH();
            cboLoaiMH.SelectedIndex = 0;
            cboSXGia.SelectedIndex = 0;
            SearchMatHang();
            cboLoaiMH.SelectedIndexChanged += txt_TextChanged;
            cboSXGia.SelectedIndexChanged += txt_TextChanged;
            hoaDonTam.MaNhanVien = nhanVien.MaNhanVien;
        }

        private void txt_TextChanged(object sender, EventArgs e)
        {
            SearchMatHang();

        }

        private void LoadProductImage(string filename)
        {
            try
            {
                string path = PRODUCT_IMAGE_FOLDER + filename;
                Image img = Image.FromFile(path);
                picMH.Image = img;
            }
            catch (Exception)
            {
                picMH.Image = null;
            }
        }

        private void LoadProductInfo(MatHangDTO matHang)
        {
            try
            {
                lblTenMH.Text = matHang.TenMatHang;
                lblGia.Text = "Giá: " + new MatHangBLL().DonGiaBan(matHang.MaMatHang).ToString("#,##0");
                lblSLTon.Text = "Số lượng tồn: " + new MatHangBLL().SoLuongTon(matHang.MaMatHang).ToString("#,##0");
                txtChiTietSP.Text = matHang.ChiTiet;
                LoadProductImage(matHang.HinhAnh);
            }
            catch
            {
                lblTenMH.Text = "## Unknown ##";
                lblGia.Text = "Giá: N/A";
                lblSLTon.Text = "Số lượng tồn: N/A";
                txtChiTietSP.Clear();
                picMH.Image = null;
            }
        }

        private void dgvMH_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvMH.SelectedRows.Count > 0)
            {
                try
                {
                    string MaMH = dgvMH.SelectedRows[0].Cells[0].Value.ToString();
                    LoadProductInfo(new MatHangBLL().GetByID(MaMH));

                    numSL.Value = numSL.Minimum;
                    numSL.Enabled = true;
                }
                catch
                {
                    LoadProductInfo(null);
                    numSL.Enabled = false;
                }
            }
        }

        private void ShowDetail()
        {
            dgvGioHang.Rows.Clear();
            int GiaTri = 0;
            int length = dsChiTiet.Count;
            for (int i = 0; i < length; i++)
            {
                DataGridViewRow row = (DataGridViewRow)dgvGioHang.Rows[0].Clone();
                row.Cells[0].Value = new MatHangBLL().GetByID(dsChiTiet[i].MaMatHang).TenMatHang;
                row.Cells[1].Value = dsChiTiet[i].SoLuong.ToString("#,##0");
                dgvGioHang.Rows.Add(row);
                double CK = new ChiTietHoaDonBLL().GetChietKhau(dsChiTiet[i]);
                int DonGia = new ChiTietHoaDonBLL().GetDonGia(dsChiTiet[i]);
                dsChiTiet[i].DonGiaBan = DonGia;
                dsChiTiet[i].ChietKhau = CK;
                GiaTri += (int)(dsChiTiet[i].SoLuong * dsChiTiet[i].DonGiaBan * (1 - dsChiTiet[i].ChietKhau));
            }
            lblTCGia.Text = GiaTri.ToString("#, ##0");
            
            btnXemGio.Enabled = length != 0;
            btnLamMoi.Enabled = length != 0;
        }

        private void AddChiTiet(ChiTietHoaDonDTO chiTiet)
        {
            if (checkChiTiet(chiTiet))
            {
                int length = dsChiTiet.Count;
                for (int i = 0; i < length; i++)
                {
                    if (dsChiTiet[i].MaMatHang == chiTiet.MaMatHang)
                    {
                        DialogResult dialogResult = MessageBox.Show("Mặt hàng đã có trong giỏ. Bạn muốn cộng dồn số lượng mua?", "CẢNH BÁO", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dialogResult == DialogResult.Yes)
                        {
                            dsChiTiet[i].SoLuong += chiTiet.SoLuong;
                            if (checkChiTiet(dsChiTiet[i]))
                            {
                                ShowDetail();
                            }
                            else
                            {
                                dsChiTiet[i].SoLuong -= chiTiet.SoLuong;
                            }
                        }
                        return;
                    }
                }
                dsChiTiet.Add(chiTiet);
                ShowDetail();
            }
        }

        private bool RemoveChiTiet(ChiTietHoaDonDTO chiTiet)
        {
            int length = dsChiTiet.Count;
            for (int i = 0; i < length; i++)
            {
                if (dsChiTiet[i].MaMatHang == chiTiet.MaMatHang)
                {
                    dsChiTiet.RemoveAt(i);
                    ShowDetail();
                    return true ;
                }
            }
            return false;
        }

       private bool UpdateChiTiet(ChiTietHoaDonDTO chiTiet)
        {
            if (checkChiTiet(chiTiet))
            {
                int length = dsChiTiet.Count;
                for (int i = 0; i < length; i++)
                {
                    if (dsChiTiet[i].MaMatHang == chiTiet.MaMatHang)
                    {
                        dsChiTiet[i].SoLuong = chiTiet.SoLuong;
                        ShowDetail();
                        return true ;
                    }
                }
            }
            return false;
        }

        private bool checkChiTiet(ChiTietHoaDonDTO chiTiet)
        {
            int SLTon = new MatHangBLL().SoLuongTon(chiTiet.MaMatHang);
            if (chiTiet.SoLuong > SLTon)
            {
                MessageBox.Show("Số lượng mua quá lớn.", "LỖI", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            ChiTietHoaDonDTO chiTiet = new ChiTietHoaDonDTO();
            chiTiet.MaMatHang = dgvMH.SelectedRows[0].Cells[0].Value.ToString();
            chiTiet.SoLuong = (short) numSL.Value;
            AddChiTiet(chiTiet);
            numSL.Value = numSL.Minimum;
        }        

        private void numSL_ValueChanged(object sender, EventArgs e)
        {
            btnThem.Enabled = numSL.Enabled && numSL.Value > 0;
        }

        private void btnLamMoi_Click(object sender, EventArgs e)
        {
            RemoveAll();
        }

        private void RemoveAll()
        {
            DialogResult dialogResult = MessageBox.Show("Bạn muốn làm trống giỏ hàng?", "CẢNH BÁO", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Yes)
            {
                dsChiTiet.Clear();
                ShowDetail();
            }
        }

        private void SetHoaDonInfo(String TenKH, string DT, DateTime NgayLap)
        {
            hoaDonTam.KhachHang = TenKH;
            hoaDonTam.DienThoai = DT;
            hoaDonTam.ThoiGianBan = NgayLap;
        }

        private void ResetAll()
        {
            cboLoaiMH.SelectedIndexChanged -= txt_TextChanged;
            cboSXGia.SelectedIndexChanged -= txt_TextChanged;

            dsMatHang = new List<MatHangDTO>();
            dsChiTiet = new List<ChiTietHoaDonDTO>();
            hoaDonTam = new HoaDonDTO();
            hoaDonTam.MaNhanVien = nhanVien.MaNhanVien;

            cboLoaiMH.SelectedIndex = 0;
            cboSXGia.SelectedIndex = 0;
            SearchMatHang();
            cboLoaiMH.SelectedIndexChanged += txt_TextChanged;
            cboSXGia.SelectedIndexChanged += txt_TextChanged;
        }
    }
}
